'use strict';

var _ = require('underscore');
var suquelizeService = require('../utils/sequelizeService');
var auth = require('../authControllers/user');
var Article = suquelizeService.models.Article;
var Category = suquelizeService.models.Category;
var resJson = require('../utils/resJson.js');
var jade = require('jade');
var path = require('path');
var fs = require('fs');
var moment = require('moment');
var Promise = require('bluebird');

var controller = {
  //生成首页文章列表
  createFirstList: {
    route: 'createFirstList',
    method: 'post',
    filter: auth.loginCheckByAjax,
    action: function(req, res, next) {

      var listFile = path.join(process.cwd(), '/frontEnd/views/public/template/blog-list-first.jade');
      var newListFile = path.join(process.cwd(), '/frontEnd/views/public/template/blog-list-first.html');

      return Article.fetchPage({
          page: 1,
          size: 10
        })
        .then(function(_art) {
          var idArray = [];
          var art = _.map(_art.rows, function(row) {
            idArray.push(row.id);
            return row.get({ plain: true });
          });

          _.map(art, function(row) {
            row.deliverTime = moment(row.deliverTime).format('YYYY-MM-DD HH:mm:ss');
          });

          var html = jade.renderFile(listFile, {
            articles: art,
            idArray: JSON.stringify(idArray)
          });

          fs.writeFile(newListFile, html, function(err) {
            if (err) {
              return resJson(res, null, err);
            } else {
              return resJson(res, null);
            }
          });
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });


    }
  },
  //生成菜单栏
  createMenu: {
    route: 'createMenu',
    method: 'post',
    filter: auth.loginCheckByAjax,
    action: function(req, res, next) {
      var indexFile = path.join(process.cwd(), '/frontEnd/views/public/index.jade');
      var newIndexFile = path.join(process.cwd(), '/frontEnd/views/public/index.html');

      return Category.findAll()
        .then(function(_cat) {
          var html = jade.renderFile(indexFile, {
            title: 'ZFH的小站 - 首页',
            categorys: _cat
          });

          fs.writeFile(newIndexFile, html, function(err) {
            if (err) {
              return resJson(res, null, err);
            } else {
              return resJson(res, null);
            }
          });
        })
        .catch(function(err) {
          return resJson(res, null, err);
        });

    }
  }
};

module.exports = controller;